import React, { useState, useEffect } from 'react';
import {
  Button,
  Card,
  Form,
  Input,
  Modal,
  Space,
  Table,
  message,
  Upload,
  Select,
  InputNumber,
  Image,
  ConfigProvider,
  Tag,
} from 'antd';
import {
  PlusOutlined,
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import {
  CarouselInfo,
  CarouselStatus,
  getCarouselPage,
  addCarousel,
  updateCarousel,
  deleteCarousel,
} from '@/services/CarouselService';
import { uploadFile } from '@/services/FileService';
import styles from './index.less';
// import zhCN from 'antd/locale/zh_CN';

const CarouselAdmin: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<CarouselInfo[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number | undefined>();
  const [imageFile, setImageFile] = useState<UploadFile[]>([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });

  // 加载数据
  const loadData = async (page = pagination.current, pageSize = pagination.pageSize) => {
    try {
      setLoading(true);
      const values = await searchForm.validateFields();
      const response = await getCarouselPage({
        pageCurrent: page,
        pageSize: pageSize,
        keyword: values.keyword,
        status: values.status,
      });
      setData(response.list);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: response.totalCount,
      });
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

    // 处理图片预览
    const handlePreview = async (file: UploadFile) => {
      const resp = file.response
      if (resp) {
        const fileId = resp.uid;
        const previewUrl = `/api/file/play/${fileId}`;
        setPreviewImage(previewUrl);
        setPreviewOpen(true);
      } else {
        const fileId = file.uid;
        const previewUrl = `/api/file/play/${fileId}`;
        setPreviewImage(previewUrl);
        setPreviewOpen(true);
      }
    };

  useEffect(() => {
    searchForm.setFieldsValue({
      status: '',
    });
    loadData();
  }, []);

  // 列定义
  const columns = [
    {
      title: '图片',
      dataIndex: 'imageId',
      key: 'imageId',
      width: '15%',
      render: (imageId: string) => (
        imageId ? (
          <Image
            src={`/api/file/play/${imageId}`}
            alt="轮播图"
            width={120}
            height={67}
            style={{ objectFit: 'cover', borderRadius: 4 }}
          />
        ) : '-'
      ),
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: '15%',
    },
    {
      title: '链接',
      dataIndex: 'linkUrl',
      key: 'linkUrl',
      width: '20%',
      ellipsis: true,
      render: (linkUrl: string) => (
        linkUrl ? (
          <a
            href={linkUrl}
            target="_blank"
            rel="noopener noreferrer"
            className={styles.link}
          >
            {linkUrl}
          </a>
        ) : '-'
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: '20%',
      ellipsis: true,
    },
    {
      title: '排序权重',
      dataIndex: 'sortOrder',
      key: 'sortOrder',
      width: '10%',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '10%',
      render: (status: CarouselStatus) => (
        <Tag color={status === CarouselStatus.ACTIVE ? 'success' : 'default'}>
          {status === CarouselStatus.ACTIVE ? '启用' : '停用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: CarouselInfo) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 处理编辑
  const handleEdit = (record: CarouselInfo) => {
    setEditingId(record.id);
    form.setFieldsValue(record);
    if (record.imageId) {
      setImageFile([{
        uid: record.imageId,
        name: 'carousel',
        status: 'done',
        url: `/api/file/play/${record.imageId}`,
      }]);
    }
    setModalVisible(true);
  };

  // 处理删除
  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个轮播图吗？删除后无法恢复。',
      onOk: async () => {
        try {
          await deleteCarousel([id]);
          message.success('删除成功');
          loadData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理文件上传
  const handleFileUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    try {
      const fileId = await uploadFile(file);
      onSuccess({
        uid: fileId,
        name: file.name,
        status: 'done',
        url: `/api/file/play/${fileId}`,
      });
    } catch (error) {
      onError(error);
      message.error('上传失败');
    }
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      const submitData = {
        ...values,
        imageId: imageFile[0]?.response?.uid || imageFile[0]?.uid,
      };

      if (editingId) {
        await updateCarousel({ ...submitData, id: editingId });
        message.success('更新成功');
      } else {
        await addCarousel(submitData);
        message.success('添加成功');
      }
      handleCancel();
      loadData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理取消
  const handleCancel = () => {
    setModalVisible(false);
    setEditingId(undefined);
    form.resetFields();
    setImageFile([]);
  };

  return (
    <ConfigProvider >
      <Card title="轮播图管理">
        <div className={styles.toolbar}>
          <Form
            form={searchForm}
            layout="inline"
            onFinish={() => loadData(1)}
            initialValues={{
              status: '',
            }}
          >
            <Form.Item name="keyword">
              <Input
                placeholder="搜索标题/描述"
                prefix={<SearchOutlined />}
                allowClear
              />
            </Form.Item>
            <Form.Item name="status">
              <Select
                placeholder="状态"
                allowClear
                style={{ width: 120 }}
                options={[
                  { label: '全部', value: '' },
                  { label: '启用', value: CarouselStatus.ACTIVE },
                  { label: '停用', value: CarouselStatus.INACTIVE },
                ]}
              />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
                <Button onClick={() => {
                  searchForm.resetFields();
                  loadData(1, 20);
                }}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setModalVisible(true)}
          >
            新增轮播图
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          scroll={{ y: 'calc(100vh - 410px)', scrollToFirstRowOnChange: false }}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['20', '50', '100'],
          }}
          onChange={(newPagination) => {
            loadData(newPagination.current, newPagination.pageSize);
          }}
        />

        <Modal
          title={editingId ? '编辑轮播图' : '新增轮播图'}
          open={modalVisible}
          onCancel={handleCancel}
          footer={null}
          width={800}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            className={styles.carouselForm}
          >
            <Form.Item
              name="title"
              label="标题"
              rules={[{ required: true, message: '请输入标题' }]}
            >
              <Input maxLength={100} placeholder="请输入轮播图标题" />
            </Form.Item>

            <Form.Item
              name="imageId"
              label="轮播图"
              rules={[{ required: true, message: '请上传轮播图' }]}
              extra="建议尺寸: 1920x600px，支持 jpg、png 格式"
            >
              <div className={styles.imageUpload}>
                <Upload
                  listType="picture-card"
                  fileList={imageFile}
                  onChange={({ fileList }) => setImageFile(fileList)}
                  customRequest={handleFileUpload}
                  maxCount={1}
                  accept="image/*"
                  onPreview={handlePreview}
                >
                  {imageFile.length === 0 && (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>上传图片</div>
                    </div>
                  )}
                </Upload>
              </div>
            </Form.Item>

            <Form.Item
              name="linkUrl"
              label="链接地址"
            >
              <Input placeholder="请输入点击轮播图后跳转的链接地址" />
            </Form.Item>

            <Form.Item
              name="description"
              label="描述"
            >
              <Input.TextArea 
                rows={4} 
                maxLength={500} 
                showCount 
                placeholder="请输入轮播图描述信息"
              />
            </Form.Item>

            <Form.Item
              name="sortOrder"
              label="排序权重"
            >
              <InputNumber 
                min={0} 
                max={999} 
                style={{ width: '100%' }} 
                placeholder="请输入排序权重，数字越大越靠前"
              />
            </Form.Item>

            <Form.Item
              name="status"
              label="状态"
              initialValue={CarouselStatus.ACTIVE}
            >
              <Select
                options={[
                  { label: '启用', value: CarouselStatus.ACTIVE },
                  { label: '停用', value: CarouselStatus.INACTIVE },
                ]}
              />
            </Form.Item>

            <Form.Item className={styles.modalFooter}>
              <Space>
                <Button onClick={handleCancel}>取消</Button>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          open={previewOpen}
          title="图片预览"
          footer={null}
          onCancel={() => setPreviewOpen(false)}
        >
          <img alt="preview" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </Card>
    </ConfigProvider>
  );
};

export default CarouselAdmin; 